﻿@{
	Layout = null;
}

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>物料产品分类管理</title>
	<link href="../scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
	<style>
		/* 基础布局 */
		.layui-form {
			padding: 20px 30px 0 0;
		}

		.layui-card-body {
			padding: 15px;
		}

		.layui-table-cell {
			height: auto;
		}

		/* 其余样式保持不变... */
		/* 树形表格自定义样式 */
		.tree-table {
			width: 100%;
			min-width: 1000px;
		}

		/* 父级行样式 */
		.parent-row {
			background-color: #f8f9fa !important;
			font-weight: 500;
			cursor: pointer;
		}

		.child-row {
			background: #fff;
		}

		.parent-row .expand-icon {
			cursor: pointer;
			margin-right: 5px;
		}

		.expand-icon.expanded {
			transform: rotate(90deg);
		}

		/* 省略重复样式... */
	</style>
</head>
<body>
	<div class="layui-card">
		<div class="layui-card-header">
			<h2>物料产品分类管理</h2>
		</div>
		<div class="layui-card-body">
			<!-- 搜索区域 -->
			<form class="layui-form search-form-responsive" lay-filter="searchForm">
				@Html.AntiForgeryToken()
				<div class="layui-row layui-col-space15">
					<div class="layui-col-md3 layui-col-sm6 layui-col-xs12">
						<div class="layui-form-item">
							<label class="layui-form-label">分类名称</label>
							<div class="layui-input-block">
								<input type="text" id="keyword" name="keyword" placeholder="请输入分类名称" class="layui-input">
							</div>
						</div>
					</div>
					<div class="layui-col-md3 layui-col-sm6 layui-col-xs12">
						<div class="layui-form-item">
							<label class="layui-form-label">是否启用</label>
							<div class="layui-input-block">
								<select id="isEnabled" name="isEnabled" lay-verify="">
									<option value="">全部</option>
									<option value="true">是</option>
									<option value="false">否</option>
								</select>
							</div>
						</div>
					</div>
					<div class="layui-col-md6 layui-col-sm12 layui-col-xs12">
						<div class="layui-form-item">
							<div class="layui-input-block" style="margin-left: 0; text-align: left;">
								<button class="layui-btn" id="searchBtn">
									<i class="layui-icon layui-icon-search"></i> 搜索
								</button>
								<button type="reset" class="layui-btn layui-btn-primary" id="resetBtn">
									<i class="layui-icon layui-icon-refresh"></i> 重置
								</button>
							</div>
						</div>
					</div>
				</div>
			</form>

			<!-- 工具栏 -->
			<div class="layui-row toolbar-responsive">
				<div class="layui-col-md12">
					<div class="layui-btn-group">
						<button class="layui-btn layui-btn-sm" id="addBtn">
							<i class="layui-icon layui-icon-add-1"></i> 新增分类
						</button>
						<button id="toggleAllBtn" class="layui-btn layui-btn-primary layui-btn-sm">展开/折叠全部</button>
					</div>
				</div>
			</div>

			<!-- 表格区域 -->
			<div class="responsive-container">
				<div class="layui-form">
					<table class="layui-table tree-table" id="materialTypeTable">
						<thead>
							<tr>
								<th width="120">分类名称</th>
								<th width="80">排序</th>
								<th width="80">是否启用</th>
								<th width="140">创建时间</th>
								<th width="120">操作</th>
							</tr>
						</thead>
						<tbody id="tableBody">
							<!-- 数据将通过JavaScript动态生成 -->
						</tbody>
					</table>
				</div>
			</div>

			<!-- 分页 -->
			<div class="pagination-container">
				<div id="pagination"></div>
			</div>

		</div>
	</div>

	<!-- 新增/修改分类模态框 -->
	<div id="editModal" style="display: none;">
		<form class="layui-form" id="editForm" lay-filter="editForm">
			<input type="hidden" name="Id" id="editId">
			<input type="hidden" name="CreateTime" id="editCreateTime">
			<div class="layui-form-item">
				<label class="layui-form-label">分类名称</label>
				<div class="layui-input-block">
					<input type="text" name="MaterialTypeName" lay-verify="required" placeholder="请输入分类名称" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">父分类</label>
				<div class="layui-input-block">
					<select name="ParentId" id="parentSelect">
						<option value="0">自当父级分类</option>
						@* <option value="1">物料产品分类</option> *@
						@* <option value="2">产品</option> *@
						@* <option value="3">半成品</option> *@
						@* <option value="4">原材料</option> *@
						@* <option value="5">成品</option> *@
					</select>
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">排序</label>
				<div class="layui-input-block">
					<input type="number" name="Index" lay-verify="required|number" placeholder="请输入排序号" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">是否启用</label>
				<div class="layui-input-block">
					<input type="radio" name="State" value="1" title="是">
					<input type="radio" name="State" value="0" title="否">
				</div>
			</div>
			<!-- <div class="layui-form-item layui-form-text">
				<label class="layui-form-label">备注</label>
				<div class="layui-input-block">
					<textarea name="Remark" placeholder="请输入备注信息" class="layui-textarea"></textarea>
				</div>
			</div> -->
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn" lay-submit lay-filter="save">保存</button>
					<button type="button" class="layui-btn layui-btn-primary" id="cancelEdit">取消</button>
				</div>
			</div>
		</form>
	</div>
	<script src="~/scripts/jquery-3.4.1.min.js"></script>
	<script src="~/scripts/layui-v2.5.6/layui/layui.all.js"></script>
	<script>
		layui.use(['form', 'layer', 'laypage'], function() {
			var form = layui.form;
			var layer = layui.layer;
			var laypage = layui.laypage;

			// 分页相关变量
			var currentPage = 1;
			var pageSize = 10;
			var totalCount = 0;
			var rawData = [];

			// 初始化加载数据
			loadMaterialTypes();

			// 加载物料分类数据（采用指定的函数风格）
			function loadMaterialTypes() {
				var keyword = $('#keyword').val().trim();
				var isEnabled = $('#isEnabled').val();

				var loadIndex = layer.load(1, {
					shade: [0.3, '#fff']
				});

				$.ajax({
					url: '/MaterialType/GetPagedList/GetPagedListAsync',
					type: 'GET',
					data: {
						keyword: keyword,
						isEnabled: isEnabled
					},
					dataType: 'json',
					success: function(res) {
						console.log("查询的返回值",res);
						layer.close(loadIndex);
						renderTable(res);
					},
					error: function(xhr, status, error) {
						layer.close(loadIndex);
						console.error('请求错误:', error);
						layer.msg('加载数据失败', {icon: 2});
						$('#tableBody').html(`
							<tr>
								<td colspan="6" class="empty-data">
									<i class="layui-icon layui-icon-face-cry"></i>
									<p>加载失败</p>
								</td>
							</tr>
						`);
					}
				});
			}

			// 渲染表格数据
			function renderTable(data) {
				var tbody = document.getElementById('tableBody');
				tbody.innerHTML = '';
				if (!data || data.length === 0) {
					// 显示空状态
					var emptyRow = document.createElement('tr');
					emptyRow.innerHTML = `
						<td colspan="6" style="text-align: center; padding: 50px; color: #999;">
							<i class="layui-icon layui-icon-face-cry" style="font-size: 48px; display: block; margin-bottom: 20px;"></i>
							暂无物料分类数据
						</td>
					`;
					tbody.appendChild(emptyRow);
					return;
				}
				var treeData = buildTree(data);
				treeData.forEach(function(item) {
					var parentRow = createParentRow(item, item.id);
					tbody.appendChild(parentRow);
					if (item.children && item.children.length > 0) {
						renderChildren(item.children, item.id);
					}
				});
			}

			// 递归渲染子节点
			function renderChildren(children, parentId) {
				children.forEach(function(child) {
					var childRow = createChildRow(child, parentId);
					document.getElementById('tableBody').appendChild(childRow);
					if (child.children && child.children.length > 0) {
						renderChildren(child.children, child.id);
					}
				});
			}

			// 构建树形结构
			function buildTree(data) {
				var map = {};
				var roots = [];

				// 先构建映射表
				data.forEach(item => {
					map[item.id] = item;
					item.children = [];
				});

				// 构建树形关系
				data.forEach(item => {
					if (item.parentId === 0 || item.parentId === null || item.parentId === item.id) {
						roots.push(item);
					} else {
						if (map[item.parentId]) {
							map[item.parentId].children.push(item);
						}
					}
				});

				return roots;
			}

			// 创建父级行
			function createParentRow(item, index) {
				var tr = document.createElement('tr');
				tr.className = 'parent-row';
				tr.setAttribute('data-id', item.id);

				var expandIcon = '<i class="layui-icon layui-icon-right expand-icon" data-id="' + item.id + '"></i>';

				tr.innerHTML = `
					<td>${expandIcon}${item.materialTypeName}</td>
					<td style="text-align: center;">${item.index}</td>
					<td style="text-align: center;"><span class="status-tag ${item.state === 1 ? 'status-enabled' : 'status-disabled'}">${item.state === 1 ? '是' : '否'}</span></td>
					<td style="text-align: center;">${formatDate(item.createTime)}</td>
					<td style="text-align: center;">
						<div class="action-buttons">
							<button class="layui-btn layui-btn-xs" onclick="editMaterialType(${item.id})">修改</button>
							<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteMaterialType(${item.id})">删除</button>
						</div>
					</td>
				`;
				return tr;
			}

			// 创建子级行
			function createChildRow(item, parentId) {
				var tr = document.createElement('tr');
				tr.className = 'child-row';
				tr.setAttribute('data-parent-id', parentId);
				tr.setAttribute('data-id', item.id);
				tr.style.display = 'none'; // 默认隐藏

				tr.innerHTML = `
					<td>${item.materialTypeName}</td>
					<td style="text-align: center;">${item.index}</td>
					<td style="text-align: center;"><span class="status-tag ${item.state === 1 ? 'status-enabled' : 'status-disabled'}">${item.state === 1 ? '是' : '否'}</span></td>
					<td style="text-align: center;">${formatDate(item.createTime)}</td>
					<td style="text-align: center;">
						<div class="action-buttons">
							<button class="layui-btn layui-btn-xs" onclick="editMaterialType(${item.id})">修改</button>
							<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteMaterialType(${item.id})">删除</button>
						</div>
					</td>
				`;
				return tr;
			}

			// 创建普通行（无子节点）
			function createNormalRow(item) {
				var tr = document.createElement('tr');

				tr.innerHTML = `
					<td>${item.materialTypeName}</td>
					<td style="text-align: center;">${item.index}</td>
					<td style="text-align: center;"><span class="status-tag ${item.state === 1 ? 'status-enabled' : 'status-disabled'}">${item.state === 1 ? '是' : '否'}</span></td>
					<td style="text-align: center;">${formatDate(item.createTime)}</td>
					<td style="text-align: center;">
						<div class="action-buttons">
							<button class="layui-btn layui-btn-xs" onclick="editMaterialType(${item.id})">修改</button>
							<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteMaterialType(${item.id})">删除</button>
						</div>
					</td>
				`;

				return tr;
			}

			// 格式化日期
			function formatDate(date) {
				if (!date) return '';
				var d = new Date(date);
				return d.getFullYear() + '-' +
					   (d.getMonth() + 1).toString().padStart(2, '0') + '-' +
					   d.getDate().toString().padStart(2, '0') + ' ' +
					   d.getHours().toString().padStart(2, '0') + ':' +
					   d.getMinutes().toString().padStart(2, '0');
			}

			// 展开/收起事件
			document.addEventListener('click', function(e) {
				if (e.target.classList.contains('expand-icon')) {
					var id = e.target.getAttribute('data-id');
					var icon = e.target;
					var childRows = document.querySelectorAll('tr[data-parent-id="' + id + '"]');
					var expanded = icon.classList.contains('expanded');
					if (expanded) {
						// 收起
						icon.classList.remove('expanded');
						icon.classList.remove('layui-icon-down');
						icon.classList.add('layui-icon-right');
						childRows.forEach(function(row) {
							row.style.display = 'none';
							// 递归收起所有下级
							collapseChildren(row.getAttribute('data-id'));
						});
					} else {
						// 展开
						icon.classList.add('expanded');
						icon.classList.remove('layui-icon-right');
						icon.classList.add('layui-icon-down');
						childRows.forEach(function(row) {
							row.style.display = '';
						});
					}
				}
			});

			function collapseChildren(parentId) {
				var childRows = document.querySelectorAll('tr[data-parent-id="' + parentId + '"]');
				childRows.forEach(function(row) {
					row.style.display = 'none';
					collapseChildren(row.getAttribute('data-id'));
				});
			}

			// 新增分类
			window.addMaterialType = function() {
				$('#editForm')[0].reset();
				$('#editId').val(0);
				$('#editModal .layui-form-label').removeAttr('style');

				// 加载父分类列表
				loadParentTypes();

				// 打开模态框
				layer.open({
					type: 1,
					title: '新增物料分类',
					area: ['400px', 'auto'],
					content: $('#editModal'),
					success: function() {
						form.render();
					}
				});
			};

			// 编辑分类
			window.editMaterialType = function(id) {
				$.ajax({
					url: '/MaterialType/GetById/GetByIdAsync',
					type: 'GET',
					data: { id: id },
					dataType: 'json',
					success: function(response) {
						if (response) {
							console.log("编辑的返回值",response);
							// $('#editId').val(response.id);
							$('[name="Id"]').val(response.id);
							$('[name="ParentId"]').val(response.parentId);
							$('[name="MaterialTypeName"]').val(response.materialTypeName);
							$('[name="Index"]').val(response.index);
							$('[name="State"][value="' + response.state + '"]').prop('checked', true);
							$('[name="CreateTime"]').val(response.createTime);
							// 重新渲染radio，确保选中
							form.render('radio');
							// 加载父分类列表
							loadParentTypes(response.id);
							// 打开模态框
							layer.open({
								type: 1,
								title: '修改物料分类',
								area: ['400px', 'auto'],
								content: $('#editModal'),
								success: function() {
									form.render();
								}
							});
						} else {
							layer.msg('获取分类信息失败', {icon: 2});
						}
					},
					error: function() {
						layer.msg('获取分类信息失败', {icon: 2});
					}
				});
			};

			// 加载父分类列表
			function loadParentTypes(excludeId = 0) {
				$.ajax({
					url: '/MaterialType/GetMaterialTypes/GetMaterialTypes',
					type: 'GET',
					dataType: 'json',
					success: function(response) {
						var select = $('#parentSelect');
						select.empty();
						select.append('<option value="0">无父分类</option>');

						function addOptions(data, level = 0) {
							data.forEach(function(item) {
								if (item.id !== excludeId) {
									var indent = '';
									for (var i = 0; i < level; i++) {
										indent += '　';
									}
									select.append('<option value="' + item.id + '">' + indent + item.materialTypeName + '</option>');

									if (item.children && item.children.length > 0) {
										addOptions(item.children, level + 1);
									}
								}
							});
						}

						addOptions(response);
						form.render('select');
					},
					error: function() {
						layer.msg('加载父分类失败', {icon: 2});
					}
				});
			}

			// 保存分类
			form.on('submit(save)', function(data) {
				var formData = data.field;
				formData.CreateTime="2025-6-10";
				console.log("保存的表单数据", formData); // 调试用，确认Id和State
				$.ajax({
					url: '/MaterialType/Save/SaveAsync',
					type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify(formData),
					dataType: 'json',
					beforeSend: function() {
						layer.load(1);
					},
					success: function(response) {
						layer.closeAll('loading');
						if (response) {
							layer.msg('保存成功', {icon: 1}, function() {
								layer.closeAll();
								loadMaterialTypes();
							});
						} else {
							layer.msg('保存失败', {icon: 2});
						}
					},
					error: function() {
						layer.closeAll('loading');
						layer.msg('保存失败', {icon: 2});
					}
				});
				return false;
			});

			// 删除分类
			window.deleteMaterialType = function(id) {
				layer.confirm('确定要删除该分类吗？删除后将同时删除其子分类', function(index) {
					$.ajax({
						url: '/MaterialType/Delete/DeleteAsync',
						type: 'POST',
						data: { id: id },
						dataType: 'json',
						success: function(response) {
							if (response) {
								layer.msg('删除成功', {icon: 1});
								loadMaterialTypes();
							} else {
								layer.msg('删除失败，可能存在关联数据', {icon: 2});
							}
						},
						error: function() {
							layer.msg('删除失败', {icon: 2});
						}
					});
					layer.close(index);
				});
			};

			// 搜索按钮点击事件
			$('#searchBtn').click(function(e) {
				e.preventDefault(); // 阻止表单提交
				loadMaterialTypes();
			});

			// 重置按钮点击事件
			document.getElementById('resetBtn').addEventListener('click', function() {
				$('#keyword').val('');
				$('#isEnabled').val('');
				form.render('select');
				setTimeout(loadMaterialTypes, 100);
			});

			// 新增按钮点击事件
			document.getElementById('addBtn').addEventListener('click', addMaterialType);

			// 取消编辑
			document.getElementById('cancelEdit').addEventListener('click', function() {
				layer.closeAll();
			});

			// 展开/折叠全部
			document.getElementById('toggleAllBtn').addEventListener('click', function() {
				var icons = document.querySelectorAll('.expand-icon');
				var anyCollapsed = Array.from(icons).some(function(icon) {
					return !icon.classList.contains('expanded');
				});
				icons.forEach(function(icon) {
					if (anyCollapsed && !icon.classList.contains('expanded')) {
						icon.click();
					}
					if (!anyCollapsed && icon.classList.contains('expanded')) {
						icon.click();
					}
				});
			});
		});
	</script>
</body>
</html>